'use strict';

const Redis = require("ioredis");
const { Store } = require("koa-session2");

class RedisStore extends Store {
  constructor(options, maxAge) {
    super();
    this.maxAge = maxAge || 1800000;
    this.redis = new Redis(options);
  }

  async get(sid) {
    let data = await this.redis.get(`SESSION_${sid}`);
    return JSON.parse(data);
  }

  async set(session, { sid = this.getID(24) } = {}) {
    try {
      // Use redis set EX to automatically drop expired sessions
      await this.redis.set(`SESSION_${sid}`, JSON.stringify(session), 'EX', this.maxAge / 1000);
    } catch (e) {}
    return sid;
  }

  async destroy(sid) {
    return await this.redis.del(`SESSION:${sid}`);
  }
}

module.exports = RedisStore;